package com.xs.ai.controller;

import com.xs.ai.dto.*;
import com.xs.ai.entity.Email;
import com.xs.ai.entity.User;
import com.xs.ai.services.AutomationWorkflowService;
import com.xs.ai.services.EmailAnalysisService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1")
@RequiredArgsConstructor
public class EmailController {

    private final EmailAnalysisService emailAnalysisService;
    private final AutomationWorkflowService workflowService;

    /**
     * 获取未读邮件列表
     */
    @GetMapping("/emails/unread")
    public ResponseEntity<List<Email>> getUnreadEmails(
            @RequestParam Long userId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "50") int size) {

        List<Email> emails = emailRepository.findUnreadByUser(userId,
                PageRequest.of(page, size));
        return ResponseEntity.ok(emails);
    }

    /**
     * 分析单封邮件
     */
    @PostMapping("/emails/{emailId}/analyze")
    public ResponseEntity<EmailAnalysisResult> analyzeEmail(
            @PathVariable Long emailId,
            @RequestParam Long userId) {

        Email email = emailRepository.findById(emailId)
                .orElseThrow(() -> new ResourceNotFoundException("邮件不存在"));

        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));

        EmailAnalysisResult result = emailAnalysisService.analyzeEmail(email, user);

        return ResponseEntity.ok(result);
    }

    /**
     * 生成回复建议
     */
    @PostMapping("/emails/{emailId}/reply-suggestions")
    public ResponseEntity<List<ReplySuggestion>> getReplySuggestions(
            @PathVariable Long emailId,
            @RequestParam Long userId) {

        Email email = emailRepository.findById(emailId)
                .orElseThrow(() -> new ResourceNotFoundException("邮件不存在"));

        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));

        List<ReplySuggestion> suggestions =
                emailAnalysisService.generateReplySuggestions(email, user);

        return ResponseEntity.ok(suggestions);
    }

    /**
     * 发送回复
     */
    @PostMapping("/emails/{emailId}/reply")
    public ResponseEntity<Map<String, String>> sendReply(
            @PathVariable Long emailId,
            @RequestBody ReplyRequest request) {

        emailService.sendReply(emailId, request.getBody(), request.getUserId());

        return ResponseEntity.ok(Map.of("status", "success", "message", "回复已发送"));
    }

    /**
     * 更新邮件优先级
     */
    @PutMapping("/emails/{emailId}/priority")
    public ResponseEntity<Void> updatePriority(
            @PathVariable Long emailId,
            @RequestBody PriorityUpdateRequest request) {

        emailService.updateUserPriority(emailId, request.getPriority());

        // 记录用户决策用于学习
        userBehaviorLearningService.recordDecision(
                request.getUserId(),
                "email_priority",
                "email",
                emailId,
                request.getAiSuggestion(),
                request.getUserChoice()
        );

        return ResponseEntity.ok().build();
    }
}
